//
//  DataSettingsVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/4/21.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit

class DataSettingsVC: RootVC {
    private let datas = [("Data Limit",""),
                         ("Data Limit Mode",""),
                         ("Total",""),
                         ("Alarm","")]
    
    private lazy var modeLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        label.right = screenWidth - 30
        label.backgroundColor = clearColor
        label.text = UserInfoManager.shared().data_volume_limit_unit
        label.textAlignment = .right
        return label
    }()
    
    private lazy var totalLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
        label.right = screenWidth - 30
        label.backgroundColor = clearColor
        if UserInfoManager.shared().data_volume_limit_unit == "Data" {
           label.text = UserInfoManager.shared().limit_data_total_size + " MB"
        }else{
            label.text = UserInfoManager.shared().limit_time_total_size + " h"
        }
        
        label.textAlignment = .right
        return label
    }()
    
    private lazy var alarmLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
        label.right = screenWidth - 30
        label.backgroundColor = clearColor
        label.text = UserInfoManager.shared().alertPercent + "%"
        label.textAlignment = .right
        return label
    }()
    
    private lazy var limitSwitch: UISwitch = {
        let sw = UISwitch(frame: CGRect(x: 0, y: 10, width: 50, height: 30))
        sw.right = screenWidth - 8
        sw.addTarget(self, action: #selector(switchChangeValue(sender:)), for: .valueChanged)
        sw.tag = 0
        if UserInfoManager.shared().data_volume_limit_switch {
         sw.isOn = true
        }
        
        return sw
    }()
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRect(x: 0, y: naviView!.bottom, width: screenWidth, height: screenHeight - naviView!.bottom), style: .grouped)
        tab.backgroundColor = whiteColor
        tab.rowHeight = 50
        tab.delegate = self
        tab.dataSource = self
        tab.separatorStyle = .none
        tab.isScrollEnabled = false
        return tab
    }()
    
    override func configView() {
        configNaviView(title: "Data Settings")
        view.addSubview(tableView)
        rightBtn?.backgroundColor = clearColor
        rightBtn?.setTitle("OK", for: .normal)
        rightBtn?.setTitleColor(whiteColor, for: .normal)
        rightBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 18)
    }
    
    @objc private func switchChangeValue(sender:UISwitch) {
        tableView.reloadData()
    }
    
    private func showModeAlert() {
        let alertView = PickerAlertView(title: "Data Limit", data: ["Time","Data"])
        alertView.handle = ({[weak self] index in
            self?.modeLabel.text = index == 0 ? "Time" : "Data"
            self?.totalLabel.text = index == 0 ? (UserInfoManager.shared().limit_time_total_size.count == 0 ? "9999" : UserInfoManager.shared().limit_time_total_size) + " h" : UserInfoManager.shared().limit_data_total_size + " MB"
        })
        let alertVC = CustomAlertVC(contentType: .animation(alertView))
        alertVC.show()
    }
    
    private func showTotalInputAlert() {
        let total = (totalLabel.text == nil ? "" : totalLabel.text!).replacingOccurrences(of: " MB", with: "").replacingOccurrences(of: " h", with: "")
        let alertView = NumInputAlertView(input: total, content: "Please enter the total traffic.")
        alertView.handle = ({[weak self] content in
            self?.totalLabel.text = content + (self!.modeLabel.text! == "Time" ? " h" : " MB")
        })
        let alertVC = CustomAlertVC(contentType: .animation(alertView))
        alertVC.show()
    }
    
    private func showAlarmInputAlert() {
        let alarm = alarmLabel.text == nil ? "0" : alarmLabel.text!.replacingOccurrences(of: "%", with: "")
        let alertView = NumInputAlertView(input: alarm, content: "Please enter the alarm-triggering traffic.")
        alertView.handle = ({[weak self] content in
            self?.alarmLabel.text = content + "%"
        })
        let alertVC = CustomAlertVC(contentType: .animation(alertView))
        alertVC.show()
    }
    
    override func rightBtnClicked(sender: UIButton) {
        let islimit = limitSwitch.isOn ? "1" : "0"
        var unit = ""
        var size = ""
        var percent = alarmLabel.text!.replacingOccurrences(of: "%", with: "")
        if modeLabel.text == "Time" {
            unit = "time"
            size = totalLabel.text!
        }else {
            unit = "data"
            size = totalLabel.text! + "_1"
        }
        if percent.count == 0 {
            percent = "90"
        }
        if size.count == 0 {
            percent = "100"
        }
        
        if Int(percent)! >= 100 {
            percent = "100"
        }
        
        size = size.replacingOccurrences(of: " MB", with: "").replacingOccurrences(of: " h", with: "")
        
        net_setLimitData(limitSwitch: islimit, unit: unit, size: size, percent: percent) {[weak self] (success) in
            
            if success {
                UserInfoManager.shared().data_volume_limit_switch = self!.limitSwitch.isOn
                if self!.modeLabel.text == "Time" {
                    UserInfoManager.shared().data_volume_limit_unit = "Time"
                }else{
                    UserInfoManager.shared().data_volume_limit_unit = "data"
                }
                
            }
            
        }
    }
}

extension DataSettingsVC : UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return limitSwitch.isOn ? datas.count : 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = datas[indexPath.row].0
        cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
        cell.textLabel?.textColor = textGray
        cell.selectionStyle = .none
        if indexPath.row > 0 {
            cell.accessoryType = .disclosureIndicator
        }
        
        modeLabel.font = cell.textLabel?.font
        modeLabel.textColor = cell.textLabel?.textColor
        totalLabel.font = cell.textLabel?.font
        totalLabel.textColor = cell.textLabel?.textColor
        alarmLabel.font = cell.textLabel?.font
        alarmLabel.textColor = cell.textLabel?.textColor
        if indexPath.row == 0 {
         cell.contentView.addSubview(limitSwitch)
        }else if indexPath.row == 1 {
            cell.contentView.addSubview(modeLabel)
        }else if indexPath.row == 2{
            cell.contentView.addSubview(totalLabel)
        }else if indexPath.row == 3 {
            cell.contentView.addSubview(alarmLabel)
        }
        
        let line = UIView(frame: CGRect(x: 8, y: 50 - 0.5, width: screenWidth - 16, height: 0.5))
        line.backgroundColor = textGray
        cell.contentView.addSubview(line)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.row > 0 else {
            return
        }
        if indexPath.row == 1 {
            showModeAlert()
        }else if indexPath.row == 2 {
            showTotalInputAlert()
        }else {
            showAlarmInputAlert()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
